<template>
  <div>
    <div class="taskCreate" v-if="showCreate">
      <van-form>
        <van-field
          v-model="show.beginTime_plan"
          label="开始时间"
          placeholder="请选择"
          input-align="right"
          readonly
          @click="onclickBeginTimePlan"
        />
        <van-field
          v-model="show.endTime_plan"
          label="结束时间"
          placeholder="请选择"
          input-align="right"
          readonly
          @click="onclickEndTimePlan"
        />
        <van-field
          v-model="show.workArea"
          label="列检地点"
          placeholder="请选择"
          input-align="right"
          readonly
          @click="onclickWorkArea"
        />
        <van-field v-model="taskInfo.workContent" label="列检内容" type="textarea" />
        <van-field
          v-model="managerShow"
          label="负责人"
          input-align="right"
          readonly
          @click="onclickRole('manager')"
        >
          <template #button>
            <van-button
              v-if="!manager.length"
              size="small"
              type="info"
              style="margin-right: 5px;"
              @click.stop="onChooseMyUser('manager')"
            >本人</van-button>
            <van-button v-if="!manager.length" size="small" plain type="warning">自定义</van-button>
          </template>
        </van-field>
        <van-field
          v-model="trainCheckerShow"
          label="列检员"
          input-align="right"
          readonly
          @click="onclickRole('trainChecker')"
        >
          <template #button>
            <van-button
              v-if="!trainChecker.length"
              size="small"
              type="info"
              style="margin-right: 5px;"
              @click.stop="onChooseMyUser('trainChecker')"
            >本人</van-button>
            <van-button v-if="!trainChecker.length" size="small" plain type="warning">自定义</van-button>
          </template>
        </van-field>
        <van-field v-model="taskInfo.comment" type="textarea" autosize label="备注" />
        <van-popup v-model="showDateTimePicker" round position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="datetime"
            title="选择日期时间"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="onConfirmDTP"
            @cancel="onCancelDTP"
          />
        </van-popup>
        <van-popup v-model="showWorkAreaPicker" round position="bottom" :style="{ height: '50%' }">
          <van-dropdown-menu>
            <van-dropdown-item
              v-model="workAreaPicker.stationPicker.select"
              :options="workAreaPicker.stationPicker.options"
              @change="onStationPickerChange"
            />
            <van-dropdown-item
              v-if="showTrackPicker"
              v-model="workAreaPicker.trackPicker.select"
              :options="workAreaPicker.trackPicker.options"
            />
          </van-dropdown-menu>
          <div class="workArea">
            <van-form>
              <van-field
                v-model="taskInfo.workAreaComment"
                label="补充内容"
                name="comments"
                type="textarea"
                autosize
                placeholder="请填写"
              />
              <div class="submit-area">
                <van-button round style="width:120px;" @click="onCancelWorkArea">取消</van-button>
                <van-button round type="info" style="width:120px;" @click="onConfirmWorkarea">确定</van-button>
              </div>
            </van-form>
          </div>
        </van-popup>
        <div class="submit-area">
          <van-button round style="width:120px;" @click="onCancelTaskCreate">取消</van-button>
          <van-button round type="info" style="width:120px;" @click="onSubmitTaskCreate">创建</van-button>
        </div>
      </van-form>
    </div>
    <router-view></router-view>
  </div>
</template>

<script>
import { getFormatDate, getFormatHourMinute, getFormatDateTime } from '@/utils/datetime'
import { getLineData } from '@/api/line_data'
import { getUserInfobyId, getDeviceInfobyId } from '../../api/userDeviceGroup'
import { convertUserInfoStruct, convertDeviceInfoStruct } from '../../utils/taskUtils'
import { createFenceByTrackNo, deleteFenceByIds } from '../../api/fence'
import { mapGetters, createNamespacedHelpers } from 'vuex'
const taskCreateStore = createNamespacedHelpers('taskCreate')
export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      fenceShowType: 'none',
      lineData: null,
      taskInfo: {
        beginTime_plan: 0,
        endTime_plan: 0,
        workAreaComment: '',
        fenceId: 0, // 暂时按只能选择一个围栏处理
        workContent: '',
        comment: ''
      },
      show: {
        beginTime_plan: '',
        endTime_plan: '',
        workArea: '',
        fence: ''
      },
      workTrack: '', // 被选中的列检股道标识（字符串：'站号_区段号'）
      trackFenceMap: new Map(), // 股道标识与生成的围栏id的Map
      showDateTimePicker: false,
      showWorkAreaPicker: false,
      curShow: '',
      minDate: new Date(2022, 1, 1),
      maxDate: new Date(2025, 12, 31),
      currentDate: new Date(),
      showTrackPicker: false,
      workAreaPicker: {
        stationPicker: {
          select: 0,
          options: [{ text: '请选择车站', value: 0 }]
        },
        trackPicker: { select: 0, options: [{ text: '请选择股道', value: 0 }] }
      }
    }
  },
  computed: {
    ...mapGetters(['userId', 'deviceId', 'taskSetting']),
    ...taskCreateStore.mapGetters(['showCreate', 'manager', 'trainChecker', 'managerShow', 'trainCheckerShow']),
    fenceShow: function () {
      return function () {
        if (this.taskInfo.fenceId) {
          return `围栏(id:${this.taskInfo.fenceId})`
        } else return ''
      }
    }
  },
  watch: {},
  created() {},
  mounted() {
    this.fillTaskCreateData()
  },
  methods: {
    ...taskCreateStore.mapMutations(['setShowCreate', 'setTaskCreateData']),
    async onChooseMyDevice(role) {
      const deviceMsg = await getDeviceInfobyId(this.deviceId)
      if (deviceMsg.code === 0) {
        const members = []
        members.push(convertDeviceInfoStruct(deviceMsg.data))
        this.setTaskCreateData({ key: role, value: members })
      }
    },
    getFenceShowType() {
      // 未选定（无）、选定了未生成（“自动生成”）、选定了已生成（围栏描述+“删除”）
      let retVal = ''
      if (this.workTrack === '') retVal = 'none'
      else {
        if (this.trackFenceMap.get(this.workTrack)) retVal = 'delete'
        else retVal = 'generate'
      }
      console.log(retVal)
      return retVal
    },
    async onChooseMyUser(role) {
      const userMsg = await getUserInfobyId(this.userId)
      if (userMsg.code === 0) {
        const members = []
        members.push(convertUserInfoStruct(userMsg.data))
        this.setTaskCreateData({ key: role, value: members })
      }
    },
    onclickRole(role) {
      this.jumpToMemberSelect(role, this[role])
    },
    jumpToMemberSelect(role, chosenItems) {
      this.setShowCreate(false)
      this.$router.push({ path: '/memberSelectLJ', query: { role, chosenItems } })
    },
    fillTaskCreateData() {
      this.taskInfo.type = 4
      // this.fillShowData(this.taskInfo)
    },
    fillShowData(taskInfo) {
      // workArea Show
      // this.show.workArea = this.generateWorkareaShow()
    },
    onclickBeginTimePlan() {
      this.showDateTimePicker = true
      this.curShow = 'beginTimePlanPicker'
    },
    onclickEndTimePlan() {
      this.showDateTimePicker = true
      this.curShow = 'endTimePlanPicker'
    },
    onclickCustomFence() {
      this.$toast('【自定义围栏功能】 正在开发中...')
    },
    getPickedStationNo() {
      return parseInt(this.workAreaPicker.stationPicker.select)
    },
    getPickedTrackId() {
      return parseInt(this.workAreaPicker.trackPicker.select)
    },
    setWorkTrack() {
      const stationNo = this.getPickedStationNo() // 车站
      const trackId = this.getPickedTrackId() // 股道
      if (stationNo && trackId) this.workTrack = `${stationNo}_${trackId}`
      else this.workTrack = ''
    },
    setFenceShow() {
      // 确保在setWorkTrack后更新
    },
    async onClickAutoFence() {
      try {
        const stationNo = this.getPickedStationNo() // 车站
        const trackId = this.getPickedTrackId() // 股道
        const fenceType = 0 // 封闭围栏
        const msg = await createFenceByTrackNo(stationNo, trackId, fenceType)
        this.taskInfo.fenceId = parseInt(msg.data.fence_id)
        // this.show.fence = `围栏(id:${msg.data.fence_id})`
        this.trackFenceMap.set(this.workTrack, msg.data.fence_id)
        this.fenceShowType = this.getFenceShowType()
        this.$toast(`生成围栏成功，id:${msg.data.fence_id}`)
      } catch (err) {
        this.$toast(`生成围栏失败：${err}`)
      }
    },
    async onClickDelFence() {
      try {
        const fenceId = this.trackFenceMap.get(this.workTrack) // 车站
        if (fenceId) {
          const msg = await deleteFenceByIds([fenceId])
          if (msg.code === 0) {
            this.trackFenceMap.delete(this.workTrack)
            this.taskInfo.fenceId = 0
            // this.show.fence = ''
            this.fenceShowType = this.getFenceShowType()

            this.$toast(`删除围栏成功，id:${fenceId}`)
          }
        } else {
          this.$toast('删除围栏失败：找不到fenceId')
        }
      } catch (err) {
        this.$toast(`删除围栏失败：${err}`)
      }
    },
    async onclickWorkArea() {
      this.showWorkAreaPicker = true
      if (!this.lineData) {
        try {
          const msg = await getLineData()
          if (msg.code === 0) {
            this.lineData = msg.data
            this.setStationOptions()
          } else {
            throw new Error('lineData Error')
          }
        } catch (err) {
          console.log(err)
        }
      }
      // if (this.workAreaPicker.stationPicker.select) {
      //   // 选择了具体车站
      //   this.setTrackOptions(this.workAreaPicker.stationPicker.select)
      // }
    },
    setStationOptions() {
      for (const id in this.lineData) {
        this.workAreaPicker.stationPicker.options.push({ text: this.lineData[id].baseInfo.stationName, value: parseInt(this.lineData[id].baseInfo.stationNo) })
      }
    },
    setTrackOptions(stationNo) {
      const initArray = [{ text: '请选择股道', value: 0 }]
      const optionsArray = Array.from(this.lineData[stationNo].tracks, (track) => {
        return { text: track.name, value: parseInt(track.id) }
      })
      this.workAreaPicker.trackPicker.options = initArray.concat(optionsArray)
    },
    onConfirmDTP(dateTime) {
      if (this.curShow === 'beginTimePlanPicker') {
        this.taskInfo.beginTime_plan = dateTime
        this.show.beginTime_plan = getFormatDate(dateTime) + ' ' + getFormatHourMinute(dateTime)
      } else if (this.curShow === 'endTimePlanPicker') {
        this.taskInfo.endTime_plan = dateTime
        this.show.endTime_plan = getFormatDate(dateTime) + ' ' + getFormatHourMinute(dateTime)
      }
      this.showDateTimePicker = false
    },
    onCancelDTP() {
      this.showDateTimePicker = false
    },
    onStationPickerChange(stationNo) {
      if (stationNo === 0) {
        this.showTrackPicker = false
      } else {
        this.showTrackPicker = true
        this.setTrackOptions(stationNo)
      }
    },
    generateWorkareaShow() {
      let showStr = ''
      const stationNo = this.getPickedStationNo() // 车站
      const trackId = this.getPickedTrackId() // 股道
      let options = this.workAreaPicker.stationPicker.options

      this.setWorkTrack() // 选定列检地点时，顺便更新各种
      this.fenceShowType = this.getFenceShowType()
      if (this.fenceShowType === 'delete') {
        this.taskInfo.fenceId = parseInt(this.trackFenceMap.get(this.workTrack))
      }

      let idx = options.findIndex((item) => item.value === stationNo)
      if (idx >= 0) {
        showStr = `${options[idx].text}`
        options = this.workAreaPicker.trackPicker.options
        idx = options.findIndex((item) => item.value === trackId)
        if (idx >= 0) {
          showStr = `${showStr},${options[idx].text}`
        }
      }
      return showStr
    },
    onConfirmWorkarea() {
      const stationNo = this.getPickedStationNo() // 车站
      const trackId = this.getPickedTrackId() // 股道
      if (stationNo === 0) {
        this.clearWorkArea()
        this.showWorkAreaPicker = false
      } else {
        if (trackId === 0) {
          this.$toast('请选择股道')
        } else {
          this.show.workArea = this.generateWorkareaShow()
          this.showWorkAreaPicker = false
        }
      }
    },
    clearWorkArea() {
      this.show.workArea = ''
      this.workTrack = ''
      this.taskInfo.fenceId = 0
      this.fenceShowType = this.getFenceShowType()
      this.workAreaPicker.trackPicker.select = 0
    },
    onCancelWorkArea() {
      this.showWorkAreaPicker = false
    },
    async onSubmitTaskCreate() {
      const task = {
        type: 7,
        state: 3,
        creater: { userId: this.userId, deviceInfo: { type: 'HT', id: this.deviceId } },
        beginTime_plan: getFormatDateTime(this.taskInfo.beginTime_plan),
        endTime_plan: getFormatDateTime(this.taskInfo.endTime_plan),
        manager: [],
        trainChecker: [],
        fenceIds: this.taskInfo.fenceId ? [this.taskInfo.fenceId] : [],
        workArea: {
          type: 1,
          area: [],
          areaComment: this.taskInfo.workAreaComment
        },
        workContent: this.taskInfo.workContent,
        comment: this.taskInfo.comment
      }

      const stationNo = this.getPickedStationNo()
      if (stationNo) {
        const stationName = this.lineData[stationNo].baseInfo.stationName
        const places = []
        const id = this.getPickedTrackId()
        if (id) {
          const index = this.lineData[stationNo].tracks.findIndex((item) => parseInt(item.id) === id)
          if (index >= 0) {
            const place = { ...this.lineData[stationNo].tracks[index] }
            place.type = 'track'
            place.id = parseInt(place.id)
            places.push(place)
          }
        }
        const areaItem = { stationNo, stationName, places }
        task.workArea.area.push(areaItem)
      }

      this.manager.forEach((item) => {
        task.manager.push({ type: item.type, id: item.id })
      })
      this.trainChecker.forEach((item) => {
        task.trainChecker.push({ type: item.type, id: item.id })
      })
      const { data } = await this.$http.post('/task/taskCreate', task)
      if (data.code === 0) {
        this.$toast('创建成功')
        this.$router.go(-1)
      } else {
        this.$toast(`创建失败${data.msg}`)
      }
    },
    onCancelTaskCreate() {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="less" scoped>
.taskCreate {
  .workArea {
    .van-cell {
      font-size: 30px;
    }
    .van-form {
      .meter {
        /deep/.van-field__label {
          width: 90px;
        }
      }
      .kilo {
        /deep/.van-field__label {
          width: 192px;
        }
      }
    }
  }
  .submit-area {
    margin: 20px 100px;
    display: flex;
    justify-content: space-between;
  }
}
</style>
